"use client"

import { useState, useEffect } from 'react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Badge } from '@/components/ui/badge';
import { Separator } from '@/components/ui/separator';
import { PBSLevelSelector, PBSLevelDisplay } from '@/components/pbs-level-selector';
import { useToast } from '@/hooks/use-toast';

interface InstanceMapping {
  id: number;
  instance_id: string;
  pbs_level_id: number;
  pbs_instance_id: string;
  created_at: string;
  level1_area: string;
  level2_category: string | null;
  level3_subitem: string;
  full_path: string;
  pbs_code: string;
}

export default function TestPBSPage() {
  const [instanceId, setInstanceId] = useState<string>('TEST-DEVICE-001');
  const [selectedPBSLevel, setSelectedPBSLevel] = useState<number>(0);
  const [currentPBSInstanceId, setCurrentPBSInstanceId] = useState<string>('');
  const [instanceMappings, setInstanceMappings] = useState<InstanceMapping[]>([]);
  const [loading, setLoading] = useState(false);
  const [pbsStats, setPbsStats] = useState<{total: number, areas: number} | null>(null);
  const { toast } = useToast();

  // 获取实例的PBS映射
  const fetchInstanceMappings = async () => {
    if (!instanceId.trim()) return;
    
    try {
      setLoading(true);
      const response = await fetch(`/api/pbs/assign?instanceId=${encodeURIComponent(instanceId)}`);
      const data = await response.json();
      
      if (data.success) {
        setInstanceMappings(data.data);
        if (data.data.length > 0) {
          const latest = data.data[0];
          setSelectedPBSLevel(latest.pbs_level_id);
          setCurrentPBSInstanceId(latest.pbs_instance_id);
        }
      } else {
        toast({
          title: "获取映射失败",
          description: data.error,
          variant: "destructive"
        });
      }
    } catch (error) {
      console.error('获取实例映射失败:', error);
      toast({
        title: "获取映射失败",
        description: "网络错误或服务器错误",
        variant: "destructive"
      });
    } finally {
      setLoading(false);
    }
  };

  // 获取PBS统计信息
  const fetchPBSStats = async () => {
    try {
      const response = await fetch('/api/pbs/levels');
      const data = await response.json();
      
      if (data.success) {
        const levels = data.data;
        const uniqueAreas = new Set(levels.map((l: any) => l.level1_area));
        setPbsStats({
          total: levels.length,
          areas: uniqueAreas.size
        });
      }
    } catch (error) {
      console.error('获取PBS统计失败:', error);
    }
  };

  useEffect(() => {
    fetchPBSStats();
  }, []);

  useEffect(() => {
    fetchInstanceMappings();
  }, [instanceId]);

  // 处理PBS层级选择
  const handlePBSSelect = (pbsLevelId: number, pbsInstanceId: string) => {
    setSelectedPBSLevel(pbsLevelId);
    setCurrentPBSInstanceId(pbsInstanceId);
    fetchInstanceMappings(); // 刷新映射列表
    
    toast({
      title: "PBS层级分配成功",
      description: `实例 ${instanceId} 已分配到PBS层级`,
    });
  };

  // 删除PBS映射
  const handleDeleteMapping = async (mappingId: number, pbsInstanceId: string) => {
    try {
      const response = await fetch('/api/pbs/assign', {
        method: 'DELETE',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          instanceId,
          pbsInstanceId
        })
      });

      const data = await response.json();
      
      if (data.success) {
        fetchInstanceMappings(); // 刷新映射列表
        if (currentPBSInstanceId === pbsInstanceId) {
          setSelectedPBSLevel(0);
          setCurrentPBSInstanceId('');
        }
        toast({
          title: "映射删除成功",
          description: "PBS层级映射已删除",
        });
      } else {
        toast({
          title: "删除失败",
          description: data.error,
          variant: "destructive"
        });
      }
    } catch (error) {
      console.error('删除映射失败:', error);
      toast({
        title: "删除失败",
        description: "网络错误或服务器错误",
        variant: "destructive"
      });
    }
  };

  return (
    <div className="container mx-auto p-6 space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold">PBS层级系统测试</h1>
          <p className="text-muted-foreground mt-2">
            测试PBS层级选择、分配和管理功能
          </p>
        </div>
        {pbsStats && (
          <div className="text-right">
            <div className="text-2xl font-bold">{pbsStats.total}</div>
            <div className="text-sm text-muted-foreground">PBS层级，{pbsStats.areas}个区域</div>
          </div>
        )}
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* 左侧：PBS层级选择 */}
        <Card>
          <CardHeader>
            <CardTitle>PBS层级选择</CardTitle>
            <CardDescription>
              为设备实例选择对应的PBS层级，系统会自动生成唯一的层级ID
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            {/* 实例ID输入 */}
            <div>
              <Label htmlFor="instance-id">设备实例ID</Label>
              <Input
                id="instance-id"
                value={instanceId}
                onChange={(e) => setInstanceId(e.target.value)}
                placeholder="输入设备实例ID..."
                className="mt-1"
              />
              <div className="text-xs text-muted-foreground mt-1">
                用于测试的虚拟设备实例ID
              </div>
            </div>

            <Separator />

            {/* PBS层级选择器 */}
            <PBSLevelSelector
              instanceId={instanceId}
              value={selectedPBSLevel}
              onSelect={handlePBSSelect}
              placeholder="选择PBS层级..."
            />

            {/* 当前分配信息 */}
            {currentPBSInstanceId && (
              <div>
                <Label>当前PBS实例ID</Label>
                <div className="mt-1">
                  <Badge variant="outline" className="font-mono">
                    {currentPBSInstanceId}
                  </Badge>
                </div>
                <div className="text-xs text-muted-foreground mt-1">
                  此ID在实例首次选择层级时生成，后续不会变化
                </div>
              </div>
            )}
          </CardContent>
        </Card>

        {/* 右侧：实例映射历史 */}
        <Card>
          <CardHeader>
            <CardTitle>实例映射历史</CardTitle>
            <CardDescription>
              查看此实例的所有PBS层级分配记录
            </CardDescription>
          </CardHeader>
          <CardContent>
            {loading ? (
              <div className="text-center py-4 text-muted-foreground">
                加载中...
              </div>
            ) : instanceMappings.length === 0 ? (
              <div className="text-center py-4 text-muted-foreground">
                暂无PBS层级分配记录
              </div>
            ) : (
              <div className="space-y-3">
                {instanceMappings.map((mapping, index) => (
                  <div
                    key={mapping.id}
                    className="border rounded p-3 space-y-2"
                  >
                    <div className="flex items-center justify-between">
                      <Badge variant={index === 0 ? "default" : "secondary"}>
                        {index === 0 ? "当前" : `历史 ${index}`}
                      </Badge>
                      <div className="text-xs text-muted-foreground">
                        {new Date(mapping.created_at).toLocaleString()}
                      </div>
                    </div>
                    
                    <div>
                      <div className="text-sm font-medium">{mapping.full_path}</div>
                      <div className="text-xs text-muted-foreground">
                        编码: {mapping.pbs_code}
                      </div>
                    </div>
                    
                    <div>
                      <div className="text-xs text-muted-foreground">PBS实例ID:</div>
                      <code className="text-xs bg-muted px-1 rounded">
                        {mapping.pbs_instance_id}
                      </code>
                    </div>

                    <div className="flex justify-end">
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={() => handleDeleteMapping(mapping.id, mapping.pbs_instance_id)}
                      >
                        删除映射
                      </Button>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </CardContent>
        </Card>
      </div>

      {/* 底部：功能说明 */}
      <Card>
        <CardHeader>
          <CardTitle>功能说明</CardTitle>
        </CardHeader>
        <CardContent className="space-y-3">
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            <div>
              <h4 className="font-semibold text-sm">🎯 层级选择</h4>
              <p className="text-xs text-muted-foreground">
                支持按区域分组浏览、搜索过滤，共{pbsStats?.total || 0}个PBS层级可选
              </p>
            </div>
            <div>
              <h4 className="font-semibold text-sm">🔗 自动分配</h4>
              <p className="text-xs text-muted-foreground">
                选择层级后自动生成唯一的PBS实例ID，确保每个实例对应的层级ID唯一且不变
              </p>
            </div>
            <div>
              <h4 className="font-semibold text-sm">📊 映射管理</h4>
              <p className="text-xs text-muted-foreground">
                支持查看历史映射、删除映射，但实例的PBS层级ID一旦生成就保持不变
              </p>
            </div>
          </div>
          
          <Separator />
          
          <div className="text-xs text-muted-foreground">
            <strong>重要说明：</strong> 
            本系统已成功导入{pbsStats?.total || 0}条PBS层级结构数据，
            涵盖{pbsStats?.areas || 0}个区域。每个设备实例选择PBS层级后，
            系统会生成一个唯一的层级ID，此ID在实例生命周期内保持不变，
            即使后续选择了其他层级也不会影响已生成的ID。
          </div>
        </CardContent>
      </Card>
    </div>
  );
}